import 'dart:async';

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/empty_widget.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../constant/app_constant.dart';
import '../../../model/expert_message.dart';
import '../../../model/member_info.dart';
import '../../../public/event_bus.dart';
import '../../../util/log.dart';
import '../order/ExpertDataPage.dart';

/// @class : client_msg_list
/// @date : 2023-02-26 13:07
/// @name : LFC
/// @description : 对话
class ClientMsgList extends StatefulWidget {
  const ClientMsgList({Key? key}) : super(key: key);

  @override
  State<ClientMsgList> createState() => _ClientMsgLIstState();
}

class _ClientMsgLIstState extends State<ClientMsgList> {
  ExpertMessage? messages;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制

  StreamSubscription? refreshSubscription;

  @override
  void initState() {
    super.initState();
    loadMessage();
    refreshSubscription =
        eventBus.on<UpdateClientMsgListEvent>().listen((event) {
      rows.clear();
      pageNum = 1;
      loadMessage(showLoading: false);
    });
  }

  int pageNum = 1;
  List<Rows> rows = [];

  void loadMessage({showLoading = true}) {
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      var memberInfo = MemberInfo.fromJson2(json);
      LogUtil.d("當前用戶的編號： ${memberInfo.data?.membersNo.toString() ?? ""}");

      final params = {
        "membersNo": memberInfo.data?.membersNo.toString() ?? "",
        "pageNum": pageNum,
      };
      if (showLoading) {
        Obj.showLoading();
      }
      Apis.getSessionList(params)
          .then((response) => {
                Obj.dismissLoading(),
                setState(() {
                  print('getSessionList response');
                  print(response);
                  messages = ExpertMessage.fromJson(response?.data);
                  rows.addAll(messages?.rows ?? []);
                  setState(() {});
                  _refreshController.refreshCompleted();
                  _refreshController.loadComplete();

                  if ((rows.length) >= (messages?.total ?? 0)) {
                    LogUtil.d("loadNoData loadNoData ${messages?.total}");
                    _refreshController.loadNoData();
                    return;
                  }
                })
              })
          .onError((error, stackTrace) => {
                _refreshController.refreshCompleted(),
                _refreshController.loadComplete(),
                Obj.dismissLoading()
              });
    }
  }

  void loadMoreMessage({showLoading = true}) {
    if (rows.length >= (messages?.total ?? 0)) {
      _refreshController.loadNoData();
      return;
    }
    pageNum += 1;
    loadMessage(showLoading: false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: () {
          loadMoreMessage();
        },
        child: _getListView(),
      ),
    );
  }

  Widget _getListView() {
    if (rows.isEmpty) {
      return const EmptyWidget(emptyText: "暫無消息");
    }
    return ListView.separated(
        shrinkWrap: true,
        itemBuilder: (context, index) {
          return item(index);
        },
        separatorBuilder: (context, index) {
          return Container(
            height: 1,
            color: Styles.c_ccc,
          );
        },
        itemCount: rows.length ?? 0);
  }

  Widget item(idx) {
    Rows item = rows[idx];
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.symmetric(vertical: Styles.magin_16),
          width: double.infinity,
          child: InkWell(
            onTap: () {
              Get.to(ExpertDataPage(item));
            },
            child: Row(
              children: [
                ImageUtils.image(item.memberImage ?? "",
                        width: 55.w,
                        height: 55.w,
                        imageType: ImageType.NETWORK,
                        radius: 30.w)
                    .setContainer(
                        margin: EdgeInsets.only(right: Styles.magin_12)),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: double.infinity,
                        child: Stack(
                          children: [
                            Text(item.adverseName ?? "",
                                style: getTextStyle(
                                  20.w,
                                  fontType: FontType.BOLD,
                                  color: Styles.c_333,
                                )),
                            Positioned(
                              top: 0,
                              right: 0,
                              child: Text(item.updateTime ?? "",
                                  style: getTextStyle(
                                    14.w,
                                    color: Styles.c_999,
                                  )),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(
                        height: 6,
                      ),
                      Text(item.projectName ?? '',
                          style: getTextStyle(
                            16.w,
                            fontType: FontType.BOLD,
                            color: Styles.c_333,
                          )),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
        Positioned(
          bottom: 0,
          right: 0,
          child: Container(
            margin: EdgeInsets.only(right: 20.w, bottom: 16.w),
            child: item.neverRead != 0
                ? Container(
                    width: 12,
                    height: 12,
                    decoration: BoxDecoration(
                        color: Colors.redAccent,
                        borderRadius: BorderRadius.circular(6)),
                  )
                : Container(),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    refreshSubscription?.cancel();
    super.dispose();
  }

  ///下拉刷新
  void _onRefresh() {
    pageNum = 1;
    rows.clear();
    eventBus.fire(UpdateMsgReadEvent());
    loadMessage();
  }
}
